import 'package:flutter/material.dart';
import '../models/moment.dart';
import '../models/filter_data.dart';
import '../services/moment_service.dart';
import '../utils/date_formatter.dart';
import 'moment_detail_page.dart';
import 'create_moment_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  late final MomentService _momentService;
  late TabController _tabController;
  late ScrollController _scrollController;
  List<Moment> _moments = [];
  bool _isLoading = false;
  bool _isLoadingMore = false;
  String? _errorMessage;
  FilterData? _filterData;
  String? _selectedTag;
  String? _selectedTime;
  int _currentPage = 1;
  final int _pageSize = 20;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(_onTabChanged);
    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);
    // 初始化MomentService，传入401回调
    _momentService = MomentService(
      onUnauthorized: _handleUnauthorized,
    );
    _loadMoments();
    _loadFilterData();
  }

  @override
  void dispose() {
    _tabController.removeListener(_onTabChanged);
    _tabController.dispose();
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 200) {
      // 距离底部200像素时开始加载
      if (!_isLoadingMore && _hasMore) {
        _loadMoreMoments();
      }
    }
  }

  void _onTabChanged() {
    if (!_tabController.indexIsChanging) {
      // 切换完成后清除筛选条件并重新加载
      setState(() {
        _selectedTag = null;
        _selectedTime = null;
        _currentPage = 1;
        _hasMore = true;
        _moments = [];
      });
      _loadMoments();
    }
  }

  // 处理401未授权，跳转到登录页
  void _handleUnauthorized() {
    Navigator.of(context).pushReplacementNamed('/login');
  }

  Future<void> _loadFilterData() async {
    try {
      final filterData = await _momentService.getFilterData();
      setState(() {
        _filterData = filterData;
      });
    } catch (e) {
      // 忽略筛选数据加载失败
    }
  }

  Future<void> _loadMoments() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
      _currentPage = 1;
      _hasMore = true;
    });

    try {
      // 判断当前是否在收藏tab（索引为1）
      final isFavorite = _tabController.index == 1 ? true : null;

      final pageResult = await _momentService.getMomentsList(
        current: _currentPage,
        size: _pageSize,
        tag: _selectedTag,
        time: _selectedTime,
        isFavorite: isFavorite,
      );
      setState(() {
        _moments = pageResult.records;
        _isLoading = false;
        _hasMore = pageResult.records.length >= _pageSize;
      });
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  Future<void> _loadMoreMoments() async {
    if (_isLoadingMore || !_hasMore) return;

    setState(() {
      _isLoadingMore = true;
    });

    try {
      final isFavorite = _tabController.index == 1 ? true : null;
      final nextPage = _currentPage + 1;

      final pageResult = await _momentService.getMomentsList(
        current: nextPage,
        size: _pageSize,
        tag: _selectedTag,
        time: _selectedTime,
        isFavorite: isFavorite,
      );

      setState(() {
        _currentPage = nextPage;
        _moments.addAll(pageResult.records);
        _isLoadingMore = false;
        _hasMore = pageResult.records.length >= _pageSize;
      });
    } catch (e) {
      setState(() {
        _isLoadingMore = false;
      });
    }
  }

  void _applyFilter({String? tag, String? time}) {
    setState(() {
      _selectedTag = tag;
      _selectedTime = time;
      _currentPage = 1;
      _hasMore = true;
      _moments = [];
    });
    _loadMoments();
    Navigator.pop(context); // 关闭侧边栏
  }

  void _clearFilter() {
    setState(() {
      _selectedTag = null;
      _selectedTime = null;
      _currentPage = 1;
      _hasMore = true;
      _moments = [];
    });
    _loadMoments();
  }

  void _clearFilterFromTitle() {
    setState(() {
      _selectedTag = null;
      _selectedTime = null;
      _currentPage = 1;
      _hasMore = true;
      _moments = [];
    });
    _loadMoments();
  }

  Future<void> _navigateToCreate() async {
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const CreateMomentPage(),
      ),
    );

    // 新增页面会直接跳转到详情页
    // 从详情页返回时不需要刷新，因为新增的内容不在当前列表中
  }

  Future<void> _navigateToRandom() async {
    try {
      // 显示加载提示
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(
          child: CircularProgressIndicator(),
        ),
      );

      final randomMoment = await _momentService.getRandomMoment();

      if (!mounted) return;

      // 关闭加载提示
      Navigator.pop(context);

      // 跳转到详情页
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => MomentDetailPage(moment: randomMoment),
        ),
      );
    } catch (e) {
      if (!mounted) return;

      // 关闭加载提示
      Navigator.pop(context);

      // 显示错误提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取随机内容失败: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    // 判断是否有筛选条件
    final hasFilter = _selectedTag != null || _selectedTime != null;
    final filterText = _selectedTag ?? _selectedTime ?? '';

    return Scaffold(
      backgroundColor: const Color(0xFFFFFFFF),
      appBar: AppBar(
        title: hasFilter
            ? GestureDetector(
                onTap: _clearFilterFromTitle,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Flexible(
                      child: Text(
                        filterText,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    const SizedBox(width: 8),
                    const Icon(Icons.close, size: 20),
                  ],
                ),
              )
            : Center(
                child: SizedBox(
                  width: 90,
                  child: TabBar(
                    controller: _tabController,
                    indicatorColor: Colors.white,
                    labelColor: Colors.white,
                    unselectedLabelColor: Colors.white70,
                    labelPadding: EdgeInsets.zero,
                    tabs: const [
                      Tab(text: '首页'),
                      Tab(icon: Icon(Icons.favorite, color: Colors.red, size: 20)),
                    ],
                  ),
                ),
              ),
        centerTitle: true,
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        leading: Builder(
          builder: (context) => IconButton(
            icon: const Icon(Icons.menu),
            onPressed: () => Scaffold.of(context).openDrawer(),
          ),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: _navigateToCreate,
          ),
        ],
      ),
      drawer: _buildDrawer(),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildBody(), // 首页 tab
          _buildBody(), // 收藏 tab
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _navigateToRandom,
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        child: const Icon(Icons.shuffle),
      ),
    );
  }

  Widget _buildDrawer() {
    return Drawer(
      child: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '筛选',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  if (_selectedTag != null || _selectedTime != null)
                    TextButton(
                      onPressed: _clearFilter,
                      child: const Text('清除'),
                    ),
                ],
              ),
            ),
            const Divider(),
            Expanded(
              child: _filterData == null
                  ? const Center(child: CircularProgressIndicator())
                  : ListView(
                      padding: const EdgeInsets.all(16),
                      children: [
                        if (_filterData!.tags.isNotEmpty) ...[
                          const Text(
                            '标签',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 8),
                          ..._filterData!.tags.map((tag) => ListTile(
                                title: Text(tag),
                                selected: _selectedTag == tag,
                                onTap: () => _applyFilter(tag: tag),
                              )),
                          const SizedBox(height: 16),
                        ],
                        if (_filterData!.times.isNotEmpty) ...[
                          const Text(
                            '时间',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 8),
                          ..._filterData!.times.map((timeItem) => ListTile(
                                title: Text(timeItem.name),
                                trailing: Text(
                                  '${timeItem.num}',
                                  style: const TextStyle(color: Colors.grey),
                                ),
                                selected: _selectedTime == timeItem.name,
                                onTap: () => _applyFilter(time: timeItem.name),
                              )),
                        ],
                      ],
                    ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              color: Colors.red,
              size: 60,
            ),
            const SizedBox(height: 16),
            Text(
              '加载失败',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            const SizedBox(height: 8),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 32),
              child: Text(
                _errorMessage!,
                textAlign: TextAlign.center,
                style: const TextStyle(color: Colors.grey),
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadMoments,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_moments.isEmpty) {
      return const Center(
        child: Text('暂无数据'),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadMoments,
      child: ListView.builder(
        controller: _scrollController,
        itemCount: _moments.length + (_hasMore ? 1 : 0),
        itemBuilder: (context, index) {
          // 加载更多指示器
          if (index == _moments.length) {
            return Container(
              padding: const EdgeInsets.all(16),
              alignment: Alignment.center,
              child: _isLoadingMore
                  ? const CircularProgressIndicator()
                  : const SizedBox.shrink(),
            );
          }


          final moment = _moments[index];
          return GestureDetector(
            onTap: () async {
              // 直接跳转到详情页，传入列表数据
              final result = await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => MomentDetailPage(moment: moment),
                ),
              );

              // 只在必要时刷新列表
              if (mounted && result != null) {
                if (result == 'deleted') {
                  // 删除操作：重新加载列表
                  _loadMoments();
                } else if (result == 'favorited' && _tabController.index == 1) {
                  // 收藏操作且在收藏tab：重新加载列表
                  _loadMoments();
                }
                // 编辑操作不刷新，保持分页状态
              }
            },
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: const Color(0xFFEEEEEE),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 第一行：时间 星期 title
                  Row(
                    children: [
                      Text(
                        DateFormatter.formatForList(moment.createdTime),
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.grey,
                        ),
                      ),
                      if (moment.title != null && moment.title!.isNotEmpty) ...[
                        const SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            moment.title!,
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF353535),
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ] else ...[
                        const Spacer(),
                      ],
                      if (moment.isFavorite) ...[
                        const SizedBox(width: 8),
                        const Icon(
                          Icons.favorite,
                          color: Colors.red,
                          size: 16,
                        ),
                      ],
                    ],
                  ),
                  const SizedBox(height: 8),
                  // 第二行：content
                  Text(
                    moment.content,
                    maxLines: 4,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                      fontSize: 14,
                      height: 1.5,
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
